package com.spic.business.vehicle.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.spic.business.hik.constant.HkConstant;
import com.spic.business.hik.utils.HkResultUtlis;
import com.spic.business.vehicle.domain.VehicleManagement;
import com.spic.business.vehicle.service.IVehicleManagementService;
import com.spic.common.core.utils.poi.ExcelUtil;
import com.spic.common.core.web.controller.BaseController;
import com.spic.common.core.web.domain.AjaxResult;
import com.spic.common.core.web.page.TableDataInfo;
import com.spic.common.log.annotation.Log;
import com.spic.common.log.enums.BusinessType;
import com.spic.common.security.annotation.PreAuthorize;
import com.spic.system.api.RemoteDeptService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;

/**
 * 车辆管理Controller
 *
 * @author 赵祥
 * @date 2022-07-17
 */
@Slf4j
@RestController
@RequestMapping("/vehicle/management")
public class VehicleManagementController extends BaseController {
    @Autowired
    private IVehicleManagementService vehicleManagementService;
    @Autowired
    private RemoteDeptService remoteDeptService;
    /**
     * 查询车辆管理列表
     */
    @GetMapping("/list")
    public TableDataInfo list(VehicleManagement vehicleManagement) {
        // 获取部门及子部门
        if (null != vehicleManagement.getManageDept() && 0 != vehicleManagement.getManageDept()) {
            List<Long> manageDepts = remoteDeptService.getDeptAndChildren(vehicleManagement.getManageDept()).getData();
            vehicleManagement.setManageDepts(manageDepts);
        }
        startPage();
        List<VehicleManagement> list = vehicleManagementService.selectVehicleManagementList(vehicleManagement);
        return getDataTable(list);
    }

    /**
     * excel 批量导入
     * @param file
     * @return
     */
    @PostMapping(value = "/importData")
    public AjaxResult importData(@RequestPart(value = "file", required = true) MultipartFile file) throws Exception
    {
        ExcelUtil<VehicleManagement> util = new ExcelUtil<VehicleManagement>(VehicleManagement.class);
        List<VehicleManagement> list = util.importExcel(file.getInputStream());
        String message = vehicleManagementService.importData(list);
        return AjaxResult.success(message);
    }

    /**
     * 下载导入模板
     *
     * @return
     */
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        InputStream inputStream = null;
        ServletOutputStream servletOutputStream = null;
        try {
            servletOutputStream = response.getOutputStream();
            response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode("车辆管理导入模板.xls", "utf8"));
            ClassPathResource classPathResource = new ClassPathResource("Excel_model/车辆管理导入模板.xls");
            inputStream = classPathResource.getInputStream();
            IOUtils.copy(inputStream, servletOutputStream);
            response.flushBuffer();
        } catch (IOException e) {
            log.info(e.getMessage());
        } catch (RuntimeException e) {
            log.info(e.getMessage());
        } finally {
            IOUtils.closeQuietly(servletOutputStream);
            IOUtils.closeQuietly(inputStream);
        }

    }

    /**
     * 导出车辆管理列表
     */
    @PreAuthorize(hasPermi = "vehicle:management:export")
    @Log(title = "车辆管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, VehicleManagement vehicleManagement) throws IOException {
        List<VehicleManagement> list = vehicleManagementService.selectVehicleManagementList(vehicleManagement);
        ExcelUtil<VehicleManagement> util = new ExcelUtil<VehicleManagement>(VehicleManagement.class);
        util.exportExcel(response, list, "车辆管理数据");
    }

    /**
     * 获取车辆管理详细信息
     */
    @PreAuthorize(hasPermi = "vehicle:management:query")
    @GetMapping(value = "/{clientid}")
    public AjaxResult getInfo(@PathVariable("clientid") Long clientid) {
        return AjaxResult.success(vehicleManagementService.selectVehicleManagementByClientid(clientid));
    }

    /**
     * 新增车辆管理
     */
    @PreAuthorize(hasPermi = "vehicle:management:add")
    @Log(title = "车辆管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody VehicleManagement vehicleManagement) {
        return toAjax(vehicleManagementService.insertVehicleManagement(vehicleManagement));
    }

    /**
     * 修改车辆管理
     */
    @PreAuthorize(hasPermi = "vehicle:management:edit")
    @Log(title = "车辆管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody VehicleManagement vehicleManagement) {
        return toAjax(vehicleManagementService.updateVehicleManagement(vehicleManagement));
    }

    /**
     * 删除车辆管理
     */
    @PreAuthorize(hasPermi = "vehicle:management:remove")
    @Log(title = "车辆管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{clientids}")
    public AjaxResult remove(@PathVariable Long[] clientids) {
        return toAjax(vehicleManagementService.deleteVehicleManagementByClientids(clientids));
    }

    /**
     *  车辆布控
     */
    @PostMapping("/alarmCar")
    public AjaxResult alarmCar(@RequestBody VehicleManagement vehicle) {
        return toAjax(vehicleManagementService.alarmCar(vehicle));
    }

    /**
     * 取消车辆布控
     */
    @GetMapping(value = "/delAlarmCar/{clientids}")
    public AjaxResult delAlarmCar(@PathVariable("clientids") Long[] clientids) {
        return AjaxResult.success(vehicleManagementService.delAlarmCar(clientids));
    }

    /**
     * 查询停车库列表
     */
    @GetMapping(value = "/parkList")
    public AjaxResult getParkList(){
        JSONArray array = new JSONArray();
        String response = HkResultUtlis.doPostStringArtemis(HkConstant.HK_PARKLIST, "{}");
        JSONObject resultJson = JSONObject.parseObject(response);
        if ("0".equals(resultJson.getString("code"))) {
            JSONArray data = resultJson.getJSONArray("data");
            for (int i = 0; i < data.size(); i++) {
                JSONObject jsonObject = data.getJSONObject(i);
                if("0".equals(jsonObject.getString("parentParkIndexCode"))) {
                    array.add(jsonObject);
                }
            }
            return AjaxResult.success(array);
        } else {
            return AjaxResult.error(resultJson.getString("msg"));
        }
    }

    @PutMapping("/carsCharge")
    public AjaxResult carsCharge(@RequestBody VehicleManagement vehicleManagement) {
        String message = vehicleManagementService.carsCharge(vehicleManagement);
        return AjaxResult.success(message);
    }

    @GetMapping("filterDirtyData")
    public AjaxResult filterDirtyData() {
        vehicleManagementService.filterDirtyData();
        return AjaxResult.success();
    }
}
